package com.hyopt.modules.app.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.hyopt.common.utils.Constant;
import com.hyopt.common.utils.DateUtils;
import com.hyopt.common.utils.FileUtils;
import com.hyopt.common.utils.R;
import com.hyopt.modules.app.entity.AlarmInfoEntity;
import com.hyopt.modules.app.form.*;
import com.hyopt.modules.app.service.AlarmInfoService;
import com.hyopt.modules.app.service.UserService;
import com.sun.javafx.collections.MappingChange;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liubin
 * @date 2020/1/3 13:26
 */
@RestController
@RequestMapping("/app/alarm")
@Api(value = "AppAlarmController", tags = {"APP报警相关接口"})
public class AppAlarmController {
  @Autowired
  private AlarmInfoService alarmInfoService;
  @Autowired
  private UserService userService;

  @PostMapping("now/list")
  @ApiOperation("当前报警信息列表")
  //不分页，去重，未处理的所有
  public R nowList(@RequestBody AlarmNowQueryForm form) throws Exception {
    Integer role = userService.selectGrouopnumber(form.getUid());
    if(role==null){
      return R.error("该用户不存在");
    }
    //如果是普通用户，查出该用户的防区
    if(role==0){
      form.setDefenceNo(userService.selectDefence(form.getUid()));
    }
    form.setAlarmStatus(Constant.AlarmStatus.UNHANDLED.getValue());
    Map<String,Object> map = new HashMap<>();
    List<AlarmListInfoVo> result = alarmInfoService.getNowList(form);
    map.put("list",result);
    AlarmHandledQueryForm handledQueryForm = new AlarmHandledQueryForm();
    BeanUtils.copyProperties(form,handledQueryForm);
    List<AlarmListInfoVo> waitList = alarmInfoService.getAllNumber(handledQueryForm);
    map.put("number",waitList.size());
    return R.ok().put("data",map);
  }

  @PostMapping("unhandled/list")
  @ApiOperation("未处理")
  //分页，不去重，未处理
  public R unhandledList(@RequestBody AlarmHandledQueryForm form) throws Exception {
    Integer role = userService.selectGrouopnumber(form.getUid());
    if(role==null){
      return R.error("该用户不存在");
    }
    if(role==0){
      form.setDefenceNo(userService.selectDefence(form.getUid()));
    }
    form.setAlarmStatus(Constant.AlarmStatus.UNHANDLED.getValue());

    List<AlarmListInfoVo> result = alarmInfoService.getHandleList(form);
    return R.ok().put("data",result);
  }

  @PostMapping("handled/list")
  @ApiOperation("已处理")
  //分页，不去重，30天，已处理
  public R handledList(@RequestBody AlarmHandledQueryForm form) throws Exception {
    Integer role = userService.selectGrouopnumber(form.getUid());
    if(role==null){
      return R.error("该用户不存在");
    }
    if(role==0){
      form.setDefenceNo(userService.selectDefence(form.getUid()));
    }
    form.setEndTime(new Date());
    form.setStartTime(DateUtils.addDateDays(new Date(),-Constant.HISTORY_SEARCH_DAY));
    form.setAlarmStatus(Constant.AlarmStatus.HANDLED.getValue());

    List<AlarmListInfoVo> result = alarmInfoService.getHandleList(form);
    return R.ok().put("data",result);
  }

  @PostMapping("total/list")
  @ApiOperation("报警统计")
  //7天，不去重，分页
  public R totalList(@RequestBody AlarmListQueryForm form) throws Exception {

    Integer role = userService.selectGrouopnumber(form.getUid());
    if(role==null){
      return R.error("该用户不存在");
    }
    if(role==0 && form.getDefenceNo()== null){
      form.setDefenceNo(userService.selectDefence(form.getUid()));
    }

    //没有结束时间
    if (form.getEndTime() == null) {
      //有开始时间
      if (form.getStartTime() != null) {
        form.setEndTime(DateUtils.addDateDays(form.getStartTime(), Constant.COUNT_SEARCH_DAY));
      }
      //没有开始时间也没有结束时间
      form.setEndTime(new Date());
      form.setStartTime(DateUtils.addDateDays(new Date(),-Constant.COUNT_SEARCH_DAY));
    } else {//有结束时间
      //没有开始时间
      if (form.getStartTime() == null) {
        form.setStartTime(DateUtils.addDateDays(form.getEndTime(), -Constant.COUNT_SEARCH_DAY));
      }
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
      form.setEndTime(DateUtil.date(DateUtil.parse(sdf.format(form.getEndTime()))));
    }

    if(form.getStartTime().getTime()>form.getEndTime().getTime()){
      return R.error("请选择正确时间");
    }
    // 先查询total
    int total = this.alarmInfoService.getTotal(form);
    List<AlarmListInfoVo> result = alarmInfoService.totalList(form);
    if(CollUtil.isNotEmpty(result)){
      return R.ok().put("data",result).put("total",total);
    }
    return R.ok().put("data",null).put("total",0);
  }

  @GetMapping("detail/{alarmId}")
  @ApiOperation("详细的报警信息")
  public R detail(@PathVariable("alarmId") @ApiParam(value = "alarmId") Integer alarmId){
    AlarmListInfoVo vo =  alarmInfoService.getDetail(alarmId);
    return R.ok().put("data",vo);
  }

  @PostMapping("list/clear")
  @ApiOperation("一键清除报警信息")
  public R listClear(@RequestBody AlarmClearForm form){
    if(form.getID().length==0){
      return R.error("请选择id");
    }
    if(alarmInfoService.listClear(form)){
      return R.ok();
    }
    return R.error();
  }

  @PostMapping("save")
  @ApiOperation("报警处理")
  public R save(@RequestBody AlarmSaveForm form) throws Exception{
    // 查询实时对象是否已被处理
    AlarmInfoEntity alarmInfoEntity = alarmInfoService.getById(form.getId());
    if(alarmInfoEntity != null && alarmInfoEntity.getAlarmStatus() == 0){
      return R.error("该报警已处理");
    }
    if(alarmInfoService.save(form)){
      return R.ok();
    }
    return R.error();
  }

  /**
   * 上传图片--报警
   *
   * @param request
   * @return
   */
  @ApiOperation("上传图片--报警")
  @PostMapping("upload/img")
  public R  updateImg(HttpServletRequest request) {
    try {
      String path = Constant.ALARM + DateUtils.format(new Date(),DateUtils.DATE_PATTERN) + "/";
      String img = FileUtils.springUpload(request,path);
        return R.ok().put("data","/img/alarm/" + DateUtils.format(new Date(),DateUtils.DATE_PATTERN) + "/" + img);
    } catch (Exception e) {
      return R.error(e.getMessage());
    }
  }

}
